package com.chinapost.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 该方法是用来进行MYSQL备份的方法，会自动读取相应的backup.properties配置文件 从该文件中获取相应的数据库的备份信息
 * 
 * @author Administrator
 * 
 */
public class ImportUtil {
	private static ImportUtil util = null;
	/**
	 * 要导入的文件名
	 */
	private String filename;
	/**
	 * log文件全路径名
	 */
	private String logfile;
	/**
	 * 导入时用到的控制文件全名 *.ctl
	 */
	private String ctlfile;
	/**
	 * 需要备份的几个基本信息
	 */
	private String database;
	private String username;
	private String password;

	private ImportUtil() {
	}

	public static ImportUtil getInstance() {
		if (util == null)
			util = new ImportUtil();
		return util;
	}

	public void setCfg(String filename, String ctlfile, String logfile, String database, String username, String password) {
		this.filename = filename;
		this.ctlfile = ctlfile;
		this.logfile = logfile;
		this.database = database;
		this.username = username;
		this.password = password;
	}

	public boolean importData() {
		//拼接sql loader命令，参考oracle  sqlldr命令说明
		String cmd = "cmd /c sqlldr userid=" + username + "/" + password + "@" + database;
		cmd += " control=\'" + ctlfile + "\'" + " log=\'" + logfile + "\'" + " rows=5000 errors=999999";
		//System.out.println(cmd);
		try {
			//调用runtime执行oracle的sql loader程序导入数据
			Process proc = Runtime.getRuntime().exec(cmd);
			//执行过程中必须读取执行过程中的输出信息，否则会卡住
			//参考网上文章http://hellsing42.iteye.com/blog/118317
			StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
			StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
			errorGobbler.start();
			outputGobbler.start();
			try {
				//等待sql loader运行完毕再返回
				proc.waitFor();
				return true;
			} catch (InterruptedException e) {
				e.printStackTrace();
				return false;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			//导入完毕删除上传的文件名和生成的临时控制文件
			File f = new File(filename);
			if (f.exists() && f.isFile()) {
				f.delete();
			}
			File f1 = new File(ctlfile);
			if (f1.exists() && f1.isFile()) {
				f1.delete();
			}
		}
	}

}
